const request = require('request')
const path = require('path')
const fs = require('fs')

const SINGLE = 1024 * 10
const SOURCE = 'http://static.micheliafigo.xyz/books/1581347142049.jpeg'

request(
  {
    method: 'HEAD',
    uri: SOURCE
  },
  (err, res) => {
    if (err) return console.error(err)
    const file = path.join(__dirname, './image.jpeg')
    try {
      fs.closeSync(fs.openSync(file, 'w'))
    } catch (err) {
      return console.error(err)
    }
    const size = Number(res.headers['content-length'])
    const length = parseInt(size / SINGLE)
    console.log(length)
    for (let i = 0; i < length; i++) {
      let start = i * SINGLE
      let end = i == length ? (i + 1) * SINGLE - 1 : size - 1
      request({
        method: 'GET',
        uri: SOURCE,
        headers: {
          range: `bytes=${start}-${end}`
        }
      })
        .on('response', resp => {
          const range = resp.headers['content-range']
          const match = /bytes ([0-9]*)-([0-9]*)/.exec(range)
          start = match[1]
          end = match[2]
        })
        .pipe(fs.createWriteStream(file, { start, end }))
    }
  }
)
